package cz.muni.fi.pa165.web.validation;

import cz.muni.fi.pa165.api.MushroomService;
import cz.muni.fi.pa165.api.dto.MushroomDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Validation class for editing MushroomDTO
 *
 * @author Matej Cimbora
 */
@Service
public class MushroomDTOEditValidator implements Validator {

    @Autowired
    private MushroomService mushroomService;

    @Override
    public boolean supports(Class<?> type) {
        return MushroomDTO.class.equals(type);
    }

    @Override
    public void validate(Object o, Errors errors) {
        MushroomDTO mushroom = (MushroomDTO) o;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "mushroom.name.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "type", "mushroom.type.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "occurenceFrom",
                "mushroom.occurenceFrom.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "occurenceTo",
                "mushroom.occurenceTo.empty");

        if (mushroom.getOccurenceFrom() != null && mushroom.getOccurenceTo() != null) {
            if (mushroom.getOccurenceFrom().ordinal() > mushroom.getOccurenceTo().ordinal()) {
                errors.rejectValue("occurenceFrom", "mushroom.occurenceFrom.wrongOrder");
                errors.rejectValue("occurenceTo", "mushroom.occurenceTo.wrongOrder");
            }
        }
    }
}
